package com.zzyl.nursing.service.impl;

import java.time.LocalDate;
import java.time.Period;
import java.util.ArrayList;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.CodeGenerator;
import com.zzyl.common.utils.bean.BeanUtils;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.*;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;

import static cn.hutool.http.ContentType.JSON;

/**
 * 入住管理Service业务层处理
 * 
 * @author bukaixinyeyaochaoren
 * @date 2025-10-10
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper,CheckIn> implements ICheckInService
{
    @Autowired
    private CheckInMapper checkInMapper;
    //注入
    @Autowired
    private CheckInConfigMapper checkInConfigMapper;
    @Autowired
    private ElderMapper elderMapper;
    @Autowired
    private ContractMapper contractMapper;
    @Autowired
    private BedMapper bedMapper;

    /**
     * 查询入住管理
     * 
     * @param id 入住管理主键
     * @return 入住管理
     */
    @Override
    public CheckIn selectCheckInById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询入住管理列表
     * 
     * @param checkIn 入住管理
     * @return 入住管理
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn)
    {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住管理
     * 
     * @param checkIn 入住管理
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn)
    {
        return save(checkIn)?1:0;
    }

    /**
     * 修改入住管理
     * 
     * @param checkIn 入住管理
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn)
    {
        return updateById(checkIn)?1:0;
    }

    /**
     * 批量删除入住管理
     * 
     * @param ids 需要删除的入住管理主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids))?1:0;
    }

    /**
     * 删除入住管理信息
     * 
     * @param id 入住管理主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id)
    {
        return removeById(id)?1:0;
    }

    /**
     *  @param dto 入住管理
     * 新增入住管理
     */
    @Override
    public int  apply(CheckInApplyDto dto) {

        //从CheckInApplyDto中获取其他四个Dto
        CheckInElderDto elderDto = dto.getCheckInElderDto();
        CheckInConfigDto configDto = dto.getCheckInConfigDto();
        CheckInContractDto contractDto = dto.getCheckInContractDto();
        List<ElderFamilyDto> elderFamilyDtoList = dto.getElderFamilyDtoList();
        //校验老人是否已入住  如果已入住直接抛异常BaseException
        //创建查询条件
        LambdaQueryWrapper<Elder> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Elder::getIdCardNo,elderDto.getIdCardNo()).eq(Elder::getStatus,4);
        //selectOne是Mybatis-plus已经实现的方法
        Elder elder = elderMapper.selectOne(lambdaQueryWrapper);
        if(elder!=null){
            throw new BaseException("该老人已入住");
        }
        //更新床位的状态
        //得到床位id
        Long bedId = configDto.getBedId();
        Bed bed = bedMapper.selectBedById(bedId);
        if(bed==null){
            throw new BaseException("请选择正确的床位");
        }
        //不为空设置状态为1
        bed.setBedStatus(1);
        //Mybatis-plus已经实现的方法
        bedMapper.updateBed(bed);
        //新增或更新老人elder   方法内容太多，抽取到下面的方法里面用Alt+Enter
        elder = saveOrUpdateElder(elderDto,bed);
        //新增合同信息  合同号要求： HT+18位数字，例：HT202501011012590001
        saveContract(contractDto,elder,configDto);
        //新增入住信息  老人家属信息存到remark字段中
        CheckIn checkIn = saveCheckIn(elder,configDto,elderFamilyDtoList);
        //新增入住配置
        saveCheckInConfig(contractDto,elder,configDto,checkIn);
        return 1;

    }

    private void saveCheckInConfig(CheckInContractDto contractDto, Elder elder, CheckInConfigDto configDto, CheckIn checkIn) {
        CheckInConfig checkInConfig = new CheckInConfig();

        checkInConfig.setCheckInId(checkIn.getId());
        checkInConfig.setNursingLevelId(configDto.getNursingLevelId());
        checkInConfig.setNursingLevelName(configDto.getNursingLevelName());
        checkInConfig.setFeeStartDate(configDto.getFeeStartDate());
        checkInConfig.setFeeEndDate(configDto.getFeeEndDate());
        checkInConfig.setDeposit(configDto.getDeposit());
        checkInConfig.setNursingFee(configDto.getNursingFee());
        checkInConfig.setBedFee(configDto.getBedFee());
        checkInConfig.setInsurancePayment(configDto.getInsurancePayment());
        checkInConfig.setGovernmentSubsidy(configDto.getGovernmentSubsidy());
        checkInConfig.setOtherFees(configDto.getOtherFees());

        checkInConfigMapper.insert(checkInConfig);
    }

    private CheckIn saveCheckIn(Elder elder, CheckInConfigDto configDto, List<ElderFamilyDto> elderFamilyDtoList) {
        CheckIn checkIn = new CheckIn();

        checkIn.setElderName(elder.getName());
        checkIn.setElderId(elder.getId());
        checkIn.setIdCardNo(elder.getIdCardNo());
        checkIn.setStartDate(configDto.getStartDate());
        checkIn.setEndDate(configDto.getEndDate());
        checkIn.setNursingLevelName(configDto.getNursingLevelName());
        checkIn.setBedNumber(elder.getBedNumber());
        checkIn.setStatus(0);  //(0: 已入住, 1: 已退住)

        // 把家属信息转成json字符串
        String jsonStr = JSONUtil.toJsonStr(elderFamilyDtoList);
        checkIn.setRemark(jsonStr);

        checkInMapper.insert(checkIn);



        return checkIn;
    }

    private void saveContract(CheckInContractDto contractDto,Elder elder,CheckInConfigDto configDto) {
        //new一个合同对象
        Contract contract = new Contract();
//        contract.setId();
        //老人的id，传入新增老人的信息
        contract.setElderId(elder.getId());
        contract.setContractName(contractDto.getContractName());
        //调用生成工具
        contract.setContractNumber("HT"+CodeGenerator.generateContractNumber());
        contract.setAgreementPath(contractDto.getAgreementPath());
        contract.setThirdPartyPhone(contractDto.getThirdPartyPhone());
        contract.setThirdPartyName(contractDto.getThirdPartyName());
        contract.setElderName(elder.getName());
        //结束开始时间在配置里面
        contract.setStartDate(configDto.getStartDate());
        contract.setEndDate(configDto.getEndDate());
        contract.setStatus(1);//已生效
        contract.setSignDate(contractDto.getSignDate());
        //解除合同，现在不填写
//        contract.setTerminationSubmitter( );
//        contract.setTerminationDate();
//        contract.setTerminationAgreementPath();
        //辅助字段
//        contract.setSortOrder();
//        contract.setSearchValue();
//        contract.setCreateBy();
//        contract.setCreateTime();
//        contract.setUpdateBy();
//        contract.setUpdateTime();
//        contract.setRemark();
//        contract.setParams();
        contractMapper.insert(contract);
    }

    private Elder saveOrUpdateElder(CheckInElderDto elderDto,Bed bed) {
        LambdaQueryWrapper<Elder> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Elder::getIdCardNo,elderDto.getIdCardNo());
        //selectOne是Mybatis-plus已经实现的方法
        Elder elder = elderMapper.selectOne(lambdaQueryWrapper);
        if(elder==null){
            elder = new Elder();
            //主键自增，不用管
//            elder.setId();
            elder.setName(elderDto.getName());
            elder.setImage(elderDto.getImage());
            elder.setIdCardNo(elderDto.getIdCardNo());
            elder.setSex(elderDto.getSex());
            elder.setStatus(1);
            elder.setPhone(elderDto.getPhone());
            elder.setBirthday(elderDto.getBirthday());
            elder.setAddress(elderDto.getAddress());
            elder.setIdCardNationalEmblemImg(elderDto.getIdCardPortraitImg());
            elder.setIdCardPortraitImg(elderDto.getIdCardNationalEmblemImg());
            //床位信息在床位状态里面写过，直接传过来bed
            elder.setBedNumber(bed.getBedNumber());
            elder.setBedId(bed.getId());
            //辅助字段，不用管
//            elder.setSearchValue();
//            elder.setCreateBy();
//            elder.setCreateTime();
//            elder.setUpdateBy();
//            elder.setUpdateTime();
//            elder.setRemark();
//            elder.setParams();
            elderMapper.insert(elder);
        }else {
            elder.setName(elderDto.getName());
            elder.setImage(elderDto.getImage());
            elder.setIdCardNo(elderDto.getIdCardNo());
            elder.setSex(elderDto.getSex());
            elder.setStatus(1);
            elder.setPhone(elderDto.getPhone());
            elder.setBirthday(elderDto.getBirthday());
            elder.setAddress(elderDto.getAddress());
            elder.setIdCardNationalEmblemImg(elder.getIdCardPortraitImg());
            elder.setIdCardPortraitImg(elder.getIdCardNationalEmblemImg());
            //床位信息在床位状态里面写过，直接传过来bed
            elder.setBedNumber(bed.getBedNumber());
            elder.setBedId(bed.getId());
            elderMapper.updateById(elder);
        }
        return elder;
    }
    /**
     * 查询入住管理列表
     *
     * @param id 入住管理
     * @return 入住管理
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public CheckInDetailVo detail(Long id) {
        //新建返回信息
        CheckInDetailVo check = new CheckInDetailVo();
        //获取入住信息
        CheckIn checkIn = checkInMapper.selectById(id);
        //获取老人Id
        Long elderId = checkIn.getElderId();
        //复制老人信息
        Elder elder = elderMapper.selectById(elderId);
        CheckInElderVo elderVo = new CheckInElderVo();
        BeanUtils.copyProperties(elder, elderVo);
        //获取年龄
        int i = DateUtil.ageOfNow(elder.getBirthday());
        elderVo.setAge(i);
        elderVo.setIdCardNationalEmblemImg(elder.getIdCardNationalEmblemImg());
        elderVo.setIdCardPortraitImg(elder.getIdCardPortraitImg());
        //复制给返回信息
        check.setCheckInElderVo(elderVo);
        //老人家属
        String remark = checkIn.getRemark();
        List<ElderFamilyVo> list = JSONUtil.toList(remark, ElderFamilyVo.class);
        //复制给返回信息
        check.setElderFamilyVoList(list);
        //配置信息
        LambdaQueryWrapper<CheckInConfig> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CheckInConfig::getCheckInId,id);
        CheckInConfig checkInConfig = checkInConfigMapper.selectOne(queryWrapper);
        CheckInConfigVo configVo = new CheckInConfigVo();
        //配置信息的始末时间是入住信息的始末时间
        configVo.setStartDate(checkIn.getStartDate());
        configVo.setEndDate(checkIn.getEndDate());
        //配置信息的床位在入住信息
        configVo.setBedNumber(checkIn.getBedNumber());
        BeanUtils.copyProperties(checkInConfig, configVo);
        //复制给返回信息
        check.setCheckInConfigVo(configVo);
        //合同信息
        LambdaQueryWrapper<Contract> queryWrapper2 = new LambdaQueryWrapper<>();
        queryWrapper2.eq(Contract::getElderId,checkIn.getElderId());
        Contract contract = contractMapper.selectOne(queryWrapper2);
        //复制给返回信息
        check.setContract(contract);
        //返回信息
        return check;
    }


}
